package com.bsg.upm.check;

import java.text.MessageFormat;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Service;

import com.bsg.upm.constant.Messages;
import com.bsg.upm.entity.UserEntity;
import com.bsg.upm.util.EncryptionUtils;

/**
 * 登录业务处理检查
 * 
 * @author HCK
 *
 */
@Service
public class LoginCheck extends BaseCheck {

	/**
	 * 登录时检查
	 * 
	 * @param paramMap
	 *            请求参数
	 * @return 检查结果
	 */
	public CheckResult checkLogin(Map<String, Object> paramMap) {
		CheckResult chkRS = new CheckResult();
		String loginName = (String) paramMap.get("loginName");
		if (StringUtils.isBlank(loginName)) {
			chkRS.setStatus(HttpStatus.SC_BAD_REQUEST);
			chkRS.setErrorMsg(MessageFormat.format(Messages.NULL_NOT_ALLOWED, "用户名"));
			return chkRS;
		}

		String password = (String) paramMap.get("password");
		if (StringUtils.isBlank(password)) {
			chkRS.setStatus(HttpStatus.SC_BAD_REQUEST);
			chkRS.setErrorMsg(MessageFormat.format(Messages.NULL_NOT_ALLOWED, "密码"));
			return chkRS;
		}

		// 密码加密
		password = EncryptionUtils.getMD5(password);
		// 根据用户名和密码获取用户信息
		UserEntity user = userDao.getUser(loginName, password);
		if (user == null) {
			chkRS.setStatus(HttpStatus.SC_BAD_REQUEST);
			chkRS.setErrorMsg("用户名或密码错误");
			return chkRS;
		}

		if (!user.getEnabled() || !"native".equals(user.getAuthType())) {
			chkRS.setStatus(HttpStatus.SC_FORBIDDEN);
			chkRS.setErrorMsg("该用户无权登录");
			return chkRS;
		}
		return chkRS;
	}

}
